Telegram Group & Telegram Channel
yield from — элегантная передача управления

Если вы пишете генераторы, которые вызывают другие генераторы — забудьте про for x in sub(): yield x. Есть способ проще и мощнее.

Оператор yield from позволяет передавать элементы из подгенератора напрямую, без лишнего кода. Но фишка не только в лаконичности — он также автоматически пробрасывает исключения и возвращаемые значения из подгенератора.

Вот классика:


def gen():
for x in range(3):
yield x

def wrapper():
for x in gen():
yield x


Можно короче и лучше:


def wrapper():
yield from gen()


Но главное — yield from пробрасывает return-значение из подгенератора (начиная с Python 3.3):


def sub():
yield 1
yield 2
return 'done'

def main():
result = yield from sub()
print('Sub returned:', result)

for _ in main():
pass
# Выведет: Sub returned: done


А ещё через yield from можно проксировать значения внутрь генератора — например, в сопрограммах:


def delegator():
result = yield from coroutine()
print('coroutine done:', result)

def coroutine():
x = yield
y = yield
return x + y

g = delegator()
next(g) # Старт
next(g) # coroutine ждет x
g.send(10) # x = 10
print(g.send(20)) # y = 20 → return 30
# Выведет: coroutine done: 30


Итог: если вы пишете генераторы — освоение yield from даст вам лаконичный синтаксис, проброс return-значений, исключений и взаимодействие на новом уровне.

👉@BookPython



tg-me.com/BookPython/3617
Create:
Last Update:

yield from — элегантная передача управления

Если вы пишете генераторы, которые вызывают другие генераторы — забудьте про for x in sub(): yield x. Есть способ проще и мощнее.

Оператор yield from позволяет передавать элементы из подгенератора напрямую, без лишнего кода. Но фишка не только в лаконичности — он также автоматически пробрасывает исключения и возвращаемые значения из подгенератора.

Вот классика:


def gen():
for x in range(3):
yield x

def wrapper():
for x in gen():
yield x


Можно короче и лучше:


def wrapper():
yield from gen()


Но главное — yield from пробрасывает return-значение из подгенератора (начиная с Python 3.3):


def sub():
yield 1
yield 2
return 'done'

def main():
result = yield from sub()
print('Sub returned:', result)

for _ in main():
pass
# Выведет: Sub returned: done


А ещё через yield from можно проксировать значения внутрь генератора — например, в сопрограммах:


def delegator():
result = yield from coroutine()
print('coroutine done:', result)

def coroutine():
x = yield
y = yield
return x + y

g = delegator()
next(g) # Старт
next(g) # coroutine ждет x
g.send(10) # x = 10
print(g.send(20)) # y = 20 → return 30
# Выведет: coroutine done: 30


Итог: если вы пишете генераторы — освоение yield from даст вам лаконичный синтаксис, проброс return-значений, исключений и взаимодействие на новом уровне.

👉@BookPython

BY Библиотека Python разработчика | Книги по питону


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/BookPython/3617

View MORE
Open in Telegram


Библиотека Python разработчика | Книги по питону Telegram | DID YOU KNOW?

Date: |

How to Use Bitcoin?

n the U.S. people generally use Bitcoin as an alternative investment, helping diversify a portfolio apart from stocks and bonds. You can also use Bitcoin to make purchases, but the number of vendors that accept the cryptocurrency is still limited. Big companies that accept Bitcoin include Overstock, AT&T and Twitch. You may also find that some small local retailers or certain websites take Bitcoin, but you’ll have to do some digging. That said, PayPal has announced that it will enable cryptocurrency as a funding source for purchases this year, financing purchases by automatically converting crypto holdings to fiat currency for users. “They have 346 million users and they’re connected to 26 million merchants,” says Spencer Montgomery, founder of Uinta Crypto Consulting. “It’s huge.”

However, analysts are positive on the stock now. “We have seen a huge downside movement in the stock due to the central electricity regulatory commission’s (CERC) order that seems to be negative from 2014-15 onwards but we cannot take a linear negative view on the stock and further downside movement on the stock is unlikely. Currently stock is underpriced. Investors can bet on it for a longer horizon," said Vivek Gupta, director research at CapitalVia Global Research.

Библиотека Python разработчика | Книги по питону from us


Telegram Библиотека Python разработчика | Книги по питону
FROM USA